package com.onlyxiahui.common.utils.base.security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * 
 * Description DES加密解密 <br>
 * Date 2020-11-09 17:07:47<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
public class SecurityDesUtil {

	/**
	 * 
	 * Description 加密 <br>
	 * Date 2020-11-09 17:03:38<br>
	 * 
	 * @param bytes
	 * @return
	 * @throws Exception
	 * @since 1.0.0
	 */
	public static byte[] encrypt(byte[] bytes) throws Exception {

		// produce key
		KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
		keyGenerator.init(56);

		SecretKey secretKey = keyGenerator.generateKey();
		byte[] keyBytes = secretKey.getEncoded();
		// convert key
		DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
		SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey convertedSecretKey = secretKeyFactory.generateSecret(desKeySpec);

		// encrypt
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, convertedSecretKey);
		byte[] outBytes = cipher.doFinal(bytes);
		return outBytes;
	}

	/**
	 * 
	 * Description 解密 <br>
	 * Date 2020-11-09 17:07:01<br>
	 * 
	 * @param bytes
	 * @return
	 * @throws Exception
	 * @since 1.0.0
	 */
	public static byte[] decrypt(byte[] bytes) throws Exception {
		// produce key
		KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
		keyGenerator.init(56);

		SecretKey secretKey = keyGenerator.generateKey();
		byte[] keyBytes = secretKey.getEncoded();
		// convert key
		DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
		SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey convertedSecretKey = secretKeyFactory.generateSecret(desKeySpec);

		// encrypt
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		// decrypt
		cipher.init(Cipher.DECRYPT_MODE, convertedSecretKey);
		byte[] outBytes = cipher.doFinal(bytes);
		return outBytes;
	}
}
